﻿using UnityEngine;
using System.Collections;

public class AnimationManager : MonoBehaviour 
{

	public SpriteManager[] allAnims;
	public bool playOnAwake;
	private bool ready;
	private SpriteManager currentAnim;
	private int count;
	private int timer;

	void Start()
	{
		currentAnim = allAnims[0];
		if(playOnAwake)
			Play();
	}

	public bool HasAnimation()
	{
		return ready;
	}
	public bool HasAnimation(string name)
	{
		if(ready)
			if(currentAnim.name == name)
				return true;

		return false;
	}

	public void Flip()
	{
		transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x),transform.localScale.y,transform.localScale.z);
	}

	void Update()
	{
		if(ready)
		{
			timer ++;

			if(timer >= currentAnim.timeRating/3)
			{
				count ++;
				timer = 0;

				if(count > currentAnim.anim.Length-1)
				{
					if(currentAnim.wrapMode == AnimWrapMode.ONCE)
						ready = false;

					count = 0;
				}


				GetComponent<SpriteRenderer>().sprite = currentAnim.anim[count];

				if(currentAnim.flipImage)
					transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x)*-1,transform.localScale.y,transform.localScale.z);
			}
		}
	}

	public void ChangeFrame(int index)
	{
		if(currentAnim != null)
		{
			if(index < currentAnim.anim.Length-1)
			{
				GetComponent<SpriteRenderer>().sprite = currentAnim.anim[index];

				if(currentAnim.flipImage)
					transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x)*-1,transform.localScale.y,transform.localScale.z);
				else
					transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x),transform.localScale.y,transform.localScale.z);

			}
		}
	}

	public void Stop()
	{
		count = 0;
		timer = 0;
		ready = false;


	}

	public void Play()
	{
		if(currentAnim != null)
		{
			Stop();
			ready = true;
		}
	}

	public void StartAnim(int index)
	{
		if(currentAnim.flipImage)
			transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x)*-1,transform.localScale.y,transform.localScale.z);
		else
			transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x),transform.localScale.y,transform.localScale.z);

		if(index < allAnims.Length-1)
		{
			currentAnim = allAnims[index];
			Play();
		}
	}

	public void StartAnim(string animName)
	{
		if(currentAnim.flipImage)
			transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x)*-1,transform.localScale.y,transform.localScale.z);
		else
			transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x),transform.localScale.y,transform.localScale.z);

		foreach (SpriteManager item in allAnims) 
		{
			if(item.name == animName)
			{
				currentAnim = item;
				Play();
				break;
			}
		}
	}

	[System.Serializable]
	public class SpriteManager
	{
		public string name;
		public int timeRating;
		public bool flipImage;
		public Sprite[] anim;
		public AnimWrapMode wrapMode;
	}
	
}
public enum AnimWrapMode
{
	ONCE,
	LOOP
}
